# 11.2 I18n and Res
The I18n
object can obtain the corresponding Res
object through the baseName
and locale
parameters. The Res
object provides APIs to retrieve internationalized data.
Here are the specific usage steps:
# Create Resource Files
- Create resource files named
i18n_en_US.properties
andi18n_zh_CN.properties
. Here,i18n
is thebaseName
of the resource file, which can be any name. In this example, we use "i18n" as thebaseName
.
# Content of i18n_en_US.properties
msg=Hello {0}, today is {1}.
1
# Content of i18n_zh_CN.properties
msg=你好 {0}, 今天是 {1}.
1
# Configuration
- In your
YourJFinalConfig
class, configure the defaultbaseName
for the resource file usingme.setI18nDefaultBaseName("i18n");
Note: Java internationalization specifications require .properties
files to be edited using a specialized editor to prevent encoding issues. One commonly used editor is Properties Editor, which can be downloaded here (opens new window).
# Code Example
Here is a code example based on the above steps:
// Get the corresponding Res object through the locale parameter "en_US"
Res resEn = I18n.use("en_US");
// Directly retrieve data
String msgEn = resEn.get("msg");
// Retrieve and format data using parameters
String msgEnFormat = resEn.format("msg", "james", new Date());
// Get the corresponding Res object through the locale parameter "zh_CN"
Res resZh = I18n.use("zh_CN");
// Directly retrieve data
String msgZh = resZh.get("msg");
// Retrieve and format data using parameters
String msgZhFormat = resZh.format("msg", "詹波", new Date());
// Additionally, I18n can also load resource files that have not been configured using me.setI18nDefaultBaseName().
// The only difference is that you need to specify the baseName parameter.
// The following example requires the creation of an "otherRes_en_US.properties" file first.
Res otherRes = I18n.use("otherRes", "en_US");
otherRes.get("msg");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Usage in JFinal Template Engine
Here is how to use it in the JFinal template engine:
#(_res.get("msg"))
1
Note: The above usage requires adding the I18nInterceptor
, which will be introduced in the next section.